//
//  WDCalendarMonthScrollView.m
//  teatCalendar
//
//  Created by iMac on 2018/3/7.
//  Copyright © 2018年 com.test. All rights reserved.
//

#import "WDCalendarMonthScrollView.h"
#import "WDCalendarPageCollectionView.h"
#import "WDCanlendarHandler.h"
#import "WDCalendarMonthModel.h"


@interface WDCalendarMonthScrollView() <UIScrollViewDelegate>

@property (nonatomic, strong) WDCalendarPageCollectionView *lastPage;
@property (nonatomic, strong) WDCalendarPageCollectionView *currentPage;
@property (nonatomic, strong) WDCalendarPageCollectionView *nextPage;
@property (nonatomic, strong) NSArray *months;

@end

@implementation WDCalendarMonthScrollView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setupInit];
    }
    return self;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    CGFloat selfWidth = self.frame.size.width;
    WDCanlendarHandler *handler = [WDCanlendarHandler sharedInstance];
    CGFloat offsetX = scrollView.contentOffset.x;
    if (offsetX == 0) {
        self.months = [handler getAllMonthsForLastPage:self.months];
    }
    else if (offsetX == selfWidth) {
        
    }
    else if (offsetX == selfWidth * 2) {
        self.months = [handler getAllMonthsForNextPage:self.months];
    }
    [self setContentOffset:CGPointMake(selfWidth, 0) animated:NO];
}

- (void)setupInit {
    self.showsVerticalScrollIndicator = NO;
    self.showsHorizontalScrollIndicator = NO;
    self.pagingEnabled = YES;
    self.bounces = NO;
    self.delegate = self;
    CGFloat selfWidth = self.frame.size.width;
    CGFloat selfHeight = self.frame.size.height;
    self.lastPage = [[WDCalendarPageCollectionView alloc] initWithFrame:CGRectMake(0, 0, selfWidth, selfHeight)];
    self.currentPage = [[WDCalendarPageCollectionView alloc] initWithFrame:CGRectMake(selfWidth, 0, selfWidth, selfHeight)];
    self.nextPage = [[WDCalendarPageCollectionView alloc] initWithFrame:CGRectMake(selfWidth * 2, 0, selfWidth, selfHeight)];
    [self addSubview:self.lastPage];
    [self addSubview:self.currentPage];
    [self addSubview:self.nextPage];
    self.months = [[WDCanlendarHandler sharedInstance] getAllMonths:[NSDate date]];
    self.contentSize = CGSizeMake(selfWidth * 3, selfHeight);
    self.contentOffset = CGPointMake(selfWidth, 0);
}

- (void)setMonths:(NSArray *)months {
    _months = months;
    for (int i = 0; i < months.count; i++) {
        WDCalendarMonthModel *monthModel = months[i];
        NSLog(@"--------%@", monthModel.pageMonth);
        if (i == 0) {
            self.lastPage.models = monthModel.dayModels;
        }
        else if (i == 1) {
            self.currentPage.models = monthModel.dayModels;
        }
        else if (i == 2) {
            self.nextPage.models = monthModel.dayModels;
        }
    }
    WDCalendarMonthModel *monthModel = months[1];
    if (self.monthChange) {
        self.monthChange(monthModel.pageMonth);
    }
}

@end
